package clearsyntax.types;

import java.util.Calendar;
import java.util.Date;

public final class DateRange extends AbstractRange<Date> {

	private final int field;
	private final Calendar calendar;

	public DateRange(Date start, Date end, int field, int step) {
		super(start, end, step);
		this.field = field;
		this.calendar = Calendar.getInstance();
		checkLength();
	}

	@Override
	public DateRange by(int step) {
		return new DateRange(start(), end(), field, step);
	}

	@Override
	public Date get(int index) {
		checkIndex(index);
		calendar.setTime(start());
		calendar.add(field, step() * index);
		return calendar.getTime();
	}

	@Override
	protected int toCode(Date value) {
		calendar.setTime(value);
		return calendar.get(field);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + start().hashCode();
		result = prime * result + end().hashCode();
		result = prime * result + field;
		result = prime * result + step();
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		final DateRange that = (DateRange) obj;
		if (!this.start().equals(that.start())) {
			return false;
		}
		if (!this.end().equals(that.end())) {
			return false;
		}
		if (this.field != that.field) {
			return false;
		}
		if (this.step() != that.step()) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return "DateRange(" + start() + ", " + end() + ", " + field + ", " + step() + ")";
	}

}